package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheim.client.pojo.ShoppingCart;
import com.itheim.client.pojo.User;
import com.itheim.client.vo.ShoppingCartVo;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.service.ShoppingCartService;
import com.itheima.util.RequestParesUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author longbosheng
 * @Date 2022/6/19 17:10
 * @PackageName:com.itheima.controller
 * @ClassName: ShoppingCartController
 * @Description: TODO
 * @Version 1.0
 */
@RestController
@Log4j2
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R addCommodity(@RequestBody ShoppingCart shoppingCart,HttpServletRequest request){
        /*获取用户的id*/
        String userId = RequestParesUtil.getRequestId(request);
        shoppingCart.setUserId(userId);
        /*判断是菜品还是套餐*/
        if (shoppingCart.getSetmealId()==null){
            return shoppingCartService.addCommodityDish(shoppingCart);
        }else {
            return shoppingCartService.addCommoditySetmeal(shoppingCart);
        }
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R cleanCommodity(HttpServletRequest request){
        String userId = RequestParesUtil.getRequestId(request);
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        shoppingCartService.remove(wrapper);
        return R.success("清空购物车成功");
    }

    /**
     * 购物车列表
     * @return
     */
    @GetMapping("/list")
    public R CommodityList(){
        List<ShoppingCart> list = shoppingCartService.list();
        if (list.size()>=0){
            return R.success(list);
        }else {
            return R.error("列表出错");
        }
    }

    /**
     * 删除购物车商品
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R delCommodity(@RequestBody ShoppingCart shoppingCart,HttpServletRequest request){
        String userId = RequestParesUtil.getRequestId(request);
        shoppingCart.setUserId(userId);
        /*判断是菜品还是套餐*/
        if (shoppingCart.getSetmealId()==null){
            return shoppingCartService.dropCommodityDish(shoppingCart);
        }else {
            return shoppingCartService.dropCommoditySetmeal(shoppingCart);
        }
    }
}
